package com.acargil.sudoku.view.listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;

import com.acargil.sudoku.model.ISudokuEngine;
import com.acargil.sudoku.model.util.ISudokuUtil;
import com.acargil.sudoku.model.util.SudokuUtilFactory;
import com.acargil.sudoku.view.ISudokuView;
import com.acargil.sudoku.view.util.MessageFactory;

public class LoadListener implements ActionListener {

	private static ActionListener instance = null;
	private ISudokuEngine model;
	private ISudokuView view;
	private ISudokuUtil util;
	
	public static ActionListener getInstance(ISudokuView view, ISudokuEngine model) {
		if (instance == null) {
			instance = new LoadListener(model, view);
		}
		
		return instance;
	}
	
	protected LoadListener(ISudokuEngine model, ISudokuView view) {
		this.model = model;
		this.view = view;
		this.util = SudokuUtilFactory.createSudokuUtil();
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		File file = this.view.getLoadFile();
		try {
			ISudokuEngine loadedModel = null;
			try {
				if (file != null) {
					loadedModel = this.util.load(new FileInputStream(file));
				}
			} catch (Exception e1) {
				MessageFactory.informationMessage("File cannot be found in this directory.\n" +
						"Path: " + file.getAbsolutePath());
				return;
			}
			
			if (loadedModel == null) {
				throw new Exception();
			}
			else {
				this.model.clearAllCellValues();
				this.model.setAllCellValues(loadedModel.getAllCellValues());
				this.view.setAllCells(this.model.getAllCellValues());
			}
		} catch (Exception ex) {
			MessageFactory.informationMessage("Game cannot be loaded!");
			return;
		}
		
		MessageFactory.informationMessage("Game is successfully loaded!");
	}

}
